package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
/**
 *
 * @author axi
 *
 */
public class ShmNewsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		boolean bRet=false;
		String[] regex={
				"http://.*.shm.com.cn/[0-9]{4}-[0-9]{1,2}/[0-9]{1,2}/content_[0-9]+.htm"};
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				bRet=true;
				break;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url=urlMeta.getUrl();
		/**
		 * 判断是否为详细页，不是详细页面直接返回空
		 */
		if (!isDetailPage(url)) {
		}
		String htmltxt=urlMeta.getHtml();
		String title="";
		String content="";
		Long date=null;
		Integer commentNum=0;
		Integer clickNum=0;
		NewsMeta news=new NewsMeta();
		Document doc=Jsoup.parse(htmltxt);

		Elements select=doc.select("div.padding");
		if(select.size() > 0){
			/**
			 * 解析标题
			 */
			Elements selectTitle=select.select("div.title");
			if(selectTitle.size() > 0){
				title=selectTitle.text();
			}
			/*
			 * 解析时间
			 */
			Elements selectDate=select.select("div.Source");
			if(selectDate.size() > 0){
				date=DateUtils.matchDate(selectDate.toString());
			}
			/**
			 * 解析内容
			 */
			Elements selectContent=select.select("div#zoom");
			if(selectContent.size() > 0){
				content=HtmlCleaner.getContentHtml(url,selectContent);
			}
			/*
			 * 解析评论数
			 */
			Elements selectComment=select.select("span#commentCount");
			if(selectComment.size() > 0){
				String comment=selectComment.text();
				try {
					commentNum=Integer.parseInt(comment);
				} catch (NumberFormatException e) {
					commentNum=0;
				}
			}
		}

		if("".equals(title)){
		}
		news.setTitle(title);
		news.setContent(content);
		news.setDate(date);
		news.setUrl(url);
		news.setType(0);
		news.setCommentNum(commentNum);
		news.setClickNum(clickNum);
		String author=doc.select("div#container div.Source").text();
		if(author!=null && author.indexOf("来源：")!=-1){
			author=StringUtils.substringBetween(author, "来源：", "评论(");
		}
		news.setAuthor(author);
		return news;
	}
	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ShmNewsAnalyse s=new ShmNewsAnalyse();
		String url="http://house.shm.com.cn/2014-02/28/content_4202946.htm";
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=s.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
